package com.arvato.admin01.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.arvato.admin01.pojo.Student;
import com.arvato.admin01.service.CacheLoader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


/**
 * @author xu yuanjun
 * @data 2020/3/29 18:39
 */
@Component
@Slf4j
public class CacheTemplateService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public <T> T findData(String key, int seconds, TypeReference<T> clazz, CacheLoader<T> cacheLoader){
        String json = redisTemplate.opsForValue().get(key);
        if (json==null||"".equals(json)||"null".equalsIgnoreCase(json)){
            synchronized (this){
                json = redisTemplate.opsForValue().get(key);
                if (json!=null||!"".equals(json)||!"null".equalsIgnoreCase(json)){
                    JSON.parseArray(json,Student.class);
                }
                T t = cacheLoader.load();
                log.info("find base " +JSON.toJSONString(t));
                //加入缓存 设置缓存时间
                redisTemplate.opsForValue().set(key, JSON.toJSONString(t), seconds, TimeUnit.SECONDS);
                return t;
            }
        }
        log.info("cache value  " +JSON.parseArray(json,Student.class));
        return JSON.parseObject(json, clazz);
    }



}
